import { defineComponent, ExtractPropTypes, onBeforeUnmount, onMounted, PropType, cloneVNode, VNode } from 'vue'
import { render } from '../_util/props-util'

const messageProps = {
  prefixCls: String,
  default: [Object, Function] as PropType<VNode | (() => VNode)>,
  duration: { default: 3000 },
  key: [String, Number]
}

export type MessageProps = Partial<ExtractPropTypes<typeof messageProps>>

export default defineComponent({
  props: messageProps,
  emits: ['close'],
  setup(props, { emit }) {
    let timer: NodeJS.Timeout

    function clearTimer() {
      clearTimeout(timer)
    }
    function retimer() {
      clearTimeout(timer)
      const { duration } = props
      if (duration) {
        timer = setTimeout(close, duration)
      }
    }

    function close() {
      emit('close')
    }

    onMounted(() => {
      retimer()
    })
    onBeforeUnmount(() => {
      clearTimer()
    })

    return () => cloneVNode(render(props.default), { onMouseenter: clearTimer, onMouseleave: retimer })
  }
})
